package com.youhome.clients.controller;

import com.youhome.common.config.SMSConfig;
import com.youhome.common.response.Result;
import com.youhome.common.response.ResultCode;
import com.youhome.service.model.*;
import com.youhome.service.service.*;
import com.youhome.utils.StringUtils;
import com.youhome.utils.ValidationUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;

/**
 * Created by chen365 on 2017/10/18.
 */
@RestController
@Api(tags = "注册，登陆，注销")
public class HomeController {
    private static final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    @Autowired
    BClientService bClientService;
    @Autowired
    private AuthenticationService authenticationService;
    @Autowired
    private LoginPersistenceService loginPersistenceService;
    @Autowired
    private BCompanyService bCompanyService;
    @Autowired
    private SMSConfig smsConfig;
    @Autowired
    private BUserService bUserService;
    @Autowired
    private BCounselorService bCounselorService;


    @Autowired
    private BShareGroupService bShareGroupService;

    /**
     * 登陆
     *
     * @param request
     * @param response
     * @param phone
     * @param code
     * @param msgid
     * @return
     */
    @ApiOperation(value = "登陆", notes = "根据 phone（手机）和 password (密码)登陆", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "phone", value = "手机", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "code", value = "短信", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msgid", value = "短信ID", required = true, paramType = "query")
    })
    @PostMapping(value = "/login")
    public Object login(HttpServletRequest request, HttpServletResponse response,
                        @RequestParam("phone") String phone,
                        @RequestParam("code") String code,
                        @RequestParam("msgid") String msgid) {

        if (!ValidationUtils.isPhone(phone)) {
            return new Result(ResultCode.ERROR_PHONE);
        }

//        if (StringUtils.isEmpty(code)) {
//            return new Result(ResultCode.EMPTY_SMS_VALIDATE_CODE);
//        }
//
//        if (StringUtils.isEmpty(msgid)) {
//            return new Result(ResultCode.EMPTY_MSGID);
//        }


        BUser bUser = bUserService.selectByPhone(phone);
        if (bUser == null) {
            return new Result(ResultCode.NOT_EXIST_USER);
        }

        UserDetails userDetails = authenticationService.loadUserByPhone(phone);


//        if (!passwordEncoder.matches(password, userDetails.getPassword())) {
//            return new Result(ResultCode.FAIL_LOGIN);
//        }

/*
        try {
            JSMSClient jsmsClient = new JSMSClient(smsConfig.getSecret(), smsConfig.getAppkey());
            ValidSMSResult result = jsmsClient.sendValidSMSCode(msgid, code);
            if (!result.getIsValid()) {
                return new Result(ResultCode.ERROR_VALIDATE_CODE);
            }
        } catch (APIConnectionException e) {
            return new Result(ResultCode.VALIDATE_CODE_FAILED);
        } catch (APIRequestException e) {
            return new Result(ResultCode.VALIDATE_CODE_FAILED);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.ERROR);
        }

        */

        Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, code, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(auth);

        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
            @Override
            public String getParameter(String name) {
                return "true";
            }
        };

        PersistentTokenBasedRememberMeServices tokenService = new PersistentTokenBasedRememberMeServices(code, authenticationService, loginPersistenceService);
        tokenService.loginSuccess(wrapper, response, auth);

        Principal principal = (Principal) userDetails;
        BUser user = principal.getUser();
        BClient bClient = bClientService.selectByUserId(user.getUserId());
        if(bClient!= null) {
            user.setName(bClient.getName());
            user.setPhoto(bClient.getPhoto());
        }

        return new Result(ResultCode.SUCCESS, user);
    }

    /**
     * 退出登陆
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "退出登陆", notes = "退出登陆", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @GetMapping(value = "/exit")
    public Object logouts(HttpServletRequest request, HttpServletResponse response) {

        System.err.println("===================logout==============================");
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        new SecurityContextLogoutHandler().logout(request, response, auth);
        if (request.getCookies() != null) {
            Arrays.stream(request.getCookies()).forEach(cookie -> {
                if (cookie.getName().equalsIgnoreCase("remember-me")) {
                    cookie.setMaxAge(0);
                    cookie.setValue(null);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            });
        }

        return new Result(ResultCode.SUCCESS);
    }


    @ApiOperation(value = "客户注册", notes = "客户注册", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "int", name = "source", value = "注册来源(1.分享注册,2.顾问创建,3.B端注册,4.C端注册)", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "id", value = " 分享组shareId/公司uuid", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msg", value = "短信", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msgId", value = "短信Id", required = false, paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "name", value = "名字", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "phone", value = "手机", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "email", value = "邮箱", required = false, paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "weiXin", value = "微信号", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "qq", value = "QQ", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "investmentObjective", value = "投资目的", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "capitalSource", value = "资金来源，国内资金，海外资金", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencyRoom", value = "房型倾向", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySite", value = "地点倾向", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencyPrice", value = "价格倾向", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySize", value = "面积倾向", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "tendencySchool", value = "学校倾向(幼儿园,小学,初中,高中,大学)", required = false, paramType = "query"),

            @ApiImplicitParam(dataType = "String", name = "province", value = "省", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "city", value = "市", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "area", value = "区", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "address", value = "详细地址", required = false, paramType = "query"),

            @ApiImplicitParam(dataType = "Date", name = "birthDate", value = "生日", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "marital", value = "婚姻，0保密，1已婚，2未婚，3离异", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "income", value = "年收入", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "jobTitle", value = "职称", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "jobType", value = "工作行业", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "sex", value = "性别，0女，1男", required = false, paramType = "query")
    })
    @PostMapping(value = "/register")
    public Object register(Integer source, String id, String msg, String msgId, String name, String email, String phone,
                           String weiXin, String qq, String investmentObjective, String capitalSource, String tendencyRoom,
                           String tendencySite, String tendencyPrice, String tendencySize, String tendencySchool, String province, String city,
                           String area, String address, Date birthDate, Integer marital, String income, String jobTitle,
                           String jobType, Integer sex) {
        System.err.println("==============================1===============================");
        //1.分享注册,2.顾问创建,3.B端注册,4.C端注册
        if (source == 1 || source == 3) {
            if (StringUtils.isEmpty(id))
                return new Result(ResultCode.ERROR_PARAMETER);
        }

        if (StringUtils.isEmpty(name))
            return new Result(ResultCode.EMPTY_CLIENT_NAME);

        if (!StringUtils.isEmpty(email)) {
            if (!ValidationUtils.isEmail(email))
                return new Result(ResultCode.ERROR_EMAIL);
        }
        if (!ValidationUtils.isPhone(phone))
            return new Result(ResultCode.ERROR_CLIENT_PHONE);

        if (bUserService.selectByPhone(phone) != null)
            return new Result(ResultCode.REGISTERED_PHONE);

        //1.分享注册,2.顾问创建,3.B端注册,4.C端注册
        if (source == 1 || source == 3 || source == 4) {
            if (StringUtils.isEmpty(msg))
                return new Result(ResultCode.EMPTY_SMS_VALIDATE_CODE);

            if (StringUtils.isEmpty(msgId))
                return new Result(ResultCode.EMPTY_MSGID);
        }
        System.err.println("=============================2================================");
        try {

            Long companyId = 0L;
            Long counselorId = 0L;

            if (source == 1 && !StringUtils.isEmpty(id)) {
                System.err.println("================================sss========================");
                BShareGroup shareGroup = bShareGroupService.selectByPrimaryKey(id);
                if (shareGroup != null) {
                    counselorId = shareGroup.getCounselorId();
                }
                System.err.println("=================================a==========================");
                BCounselor counselor = bCounselorService.selectByPrimaryKey(counselorId);
                companyId = counselor.getCompanyId();

                if (counselor == null) {
                    return new Result(ResultCode.COUNSELOR_INEXISTENCE);
                }
                System.err.println("=================================b===========================");
                if (bClientService.isExist(phone, counselor.getCompanyId()) > 0) {
                    return new Result(ResultCode.CLIENT_REGISTERED_WITH_COUNSELOR);
                }
            }
            System.err.println("=================================3============================");
            if (source == 2) {
                BUser currentUser = bUserService.getCurrentUser();
                if (currentUser == null) {
                    return new Result(ResultCode.EXPIRED_LOGIN);
                }
                BCounselor counselor = bCounselorService.selectByUserId(currentUser.getUserId());

                if (counselor == null) {
                    return new Result(ResultCode.COUNSELOR_INEXISTENCE);
                }
                companyId = counselor.getCompanyId();
                counselorId = counselor.getCounselorId();
            }

            if (source == 3 && !StringUtils.isEmpty(id)) {
                BCompany company = bCompanyService.selectByUUID(id);
                if (company == null) {
                    return new Result(ResultCode.NOT_EXIST_COMPANY);
                }
                companyId = company.getCompanyId();

                if (bClientService.isExist(phone, companyId) > 0) {
                    return new Result(ResultCode.CLIENT_REGISTERED_WITH_COUNSELOR);
                }
            }
            System.err.println("====================================4=========================");
            BUser user = bUserService.selectByPhone(phone);
            if (user == null) {
                BUser bUser = new BUser();
                bUser.setPhone(phone);
                bUser.setCtime(new Date());
                bUser.setEnabled(true);
                user = bUserService.create(bUser);

                BUserRole userRole = new BUserRole();
                userRole.setUserId(user.getUserId());
                userRole.setRoleId(3L); //3	ROLE_CLIENT	客户

                bUserService.create(userRole);
            }
            Long userId = user.getUserId();

            BClient client = new BClient();
            client.setUserId(userId);
            client.setCompanyId(companyId);
            client.setCounselorId(counselorId);
            client.setPhone(phone);

            if (bClientService.isExist(phone, counselorId) > 0) {
                return new Result(ResultCode.CLIENT_REGISTERED_WITH_COUNSELOR);
            }
            System.err.println("=========================5====================================");
            client.setName(name);
            client.setEmail(email);
            client.setSource(StringUtils.getSourceText(source));

            //1.分享注册,2.顾问创建,3.B端注册,4.C端注册
            if (source == 1) {
                client.setSourceShareGorupUUID(id);
            } else if (source == 3) {
                client.setCompanyUUID(id);
            }

            if (!StringUtils.isEmpty(weiXin)) {
                client.setWeixin(weiXin);
            }
            if (!StringUtils.isEmpty(qq)) {
                client.setQq(qq);
            }
            if (!StringUtils.isEmpty(investmentObjective)) {
                client.setInvestmentObjective(investmentObjective);
            }
            if (!StringUtils.isEmpty(capitalSource)) {
                client.setCapitalSource(capitalSource);
            }
            if (!StringUtils.isEmpty(tendencyRoom)) {
                client.setTendencyRoom(tendencyRoom);
            }
            if (!StringUtils.isEmpty(tendencySite)) {
                client.setTendencySite(tendencySite);
            }
            if (!StringUtils.isEmpty(tendencyPrice)) {
                client.setTendencyPrice(tendencyPrice);
            }
            if (!StringUtils.isEmpty(tendencySize)) {
                client.setTendencySize(tendencySize);
            }
            if (!StringUtils.isEmpty(tendencySchool)) {
                client.setTendencySchool(tendencySchool);
            }
            if (!StringUtils.isEmpty(province)) {
                client.setProvince(province);
            }
            if (!StringUtils.isEmpty(city)) {
                client.setCity(city);
            }
            if (!StringUtils.isEmpty(area)) {
                client.setArea(area);
            }
            if (!StringUtils.isEmpty(address)) {
                client.setAddress(address);
            }
            if (!StringUtils.isEmpty(birthDate)) {
                client.setBirthdate(birthDate);
            }
            if (!StringUtils.isEmpty(marital)) {
                client.setMarital(marital);
            }
            if (!StringUtils.isEmpty(income)) {
                client.setIncome(income);
            }
            if (!StringUtils.isEmpty(jobTitle)) {
                client.setJobTitle(jobTitle);
            }
            if (!StringUtils.isEmpty(jobType)) {
                client.setJobType(jobType);
            }
            if (!StringUtils.isEmpty(sex)) {
                client.setSex(sex);
            } else {
                client.setSex(0);
            }
            System.err.println("====================================6=========================");
            //1.分享注册,2.顾问创建,3.B端注册,4.C端注册
            if (source == 2) {
                if (bClientService.create(client) == 1) {
                    return new Result(ResultCode.SUCCESS, client);
                }
            }
            //1.分享注册,2.顾问创建,3.B端注册,4.C端注册
            if (source == 1 || source == 3 || source == 4) {
//                JSMSClient jsmsClient = new JSMSClient(smsConfig.getSecret(), smsConfig.getAppkey());
//                ValidSMSResult result = jsmsClient.sendValidSMSCode(msgId, msg);
//                if (result.getIsValid()) {
//                    if (bClientService.save(client) == 1) {
//                        return new Result(ResultCode.SUCCESS, client);
//                    }
//                } else {
//                    return new Result(ResultCode.ERROR_VALIDATE_CODE);
//                }

                if (bClientService.create(client) == 1) {
                    return new Result(ResultCode.SUCCESS, client);
                }
            }

        }

        /*catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
            Integer ErrorCode = e.getErrorCode();
            if (ErrorCode == 50010) {
                return new Result(ResultCode.CAPTCHA_CODE);
            }
            if (ErrorCode == 50011) {
                return new Result(ResultCode.VERIFICATION_CODE_EXPIRATION);
            }
            if (ErrorCode == 50012) {
                return new Result(ResultCode.VERIFICATION_CODE_HAS_BEEN_VALIDATED);
            }
            if (ErrorCode == 50014) {
                return new Result(ResultCode.CAN_SEND_SHORT_MESSAGE_MARGIN_SHORT);
            }
            if (ErrorCode == 50015) {
                return new Result(ResultCode.VERIFY_CODE_IS_EMPTY);
            }
            if (ErrorCode == 50034) {
                return new Result(ResultCode.SEND_REPEATEDLY);
            }
        }

        */ catch (Exception e) {
            e.printStackTrace();
        }
        System.err.println("====================================7=========================");
        return new Result(ResultCode.FAIL);
    }
}
